package middleware

import (
	"api/internal/types"
	"api/pkg"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		get := r.Header.Get("token")
		if get != "" {
			resp := types.Response{
				Code: 0,
				Msg:  "token为空，用未登录",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
		token, s := pkg.GerToken(get)

		if s != "" {
			resp := types.Response{
				Code: 0,
				Msg:  s,
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
		r.ParseForm()
		r.Form.Set("userid", token["userid"].(string))

		// Passthrough to next handler if need
		next(w, r)
	}
}
